package our.pack;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MediaTekstActivity extends Activity {

	private Button save;
	private EditText titel, inhoud;
	private static File PATH = Environment.getExternalStorageDirectory();
	private MyPoint point;
	private MetaDataDataSource metaDataDatasource;
	
	/**
	 * makes a textfile and saves it in the sdcard
	 */
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mediatekst);
		
		//initialize the UI
		save = (Button) findViewById(R.id.saveButton);
		titel = (EditText) findViewById(R.id.addTekstTitel);
		inhoud = (EditText) findViewById(R.id.addTekstInhoud);
		
		//get the point where it's made
		Intent i = getIntent();
		Bundle b = i.getExtras();
		point = (MyPoint)b.get("Point");
		
		//db
		metaDataDatasource = new MetaDataDataSource(this);
		metaDataDatasource.open();
		
		save.setOnClickListener(new OnClickListener(){

			//saves it on the sdcard and database
			public void onClick(View v) {
				
				//saves it on the sdcard
				File file = new File(PATH, "/" + titel.getText().toString()+ ".txt");
				
				try {
					FileWriter writer = new FileWriter(file);
					writer.append(inhoud.getText().toString());
					writer.flush();
					writer.close();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				metaDataDatasource.open();
				
				//set the date
				String[] ids = TimeZone.getAvailableIDs(+1 * 60 * 60 * 1000);					
				SimpleTimeZone cest = new SimpleTimeZone(+1 * 60 * 60 * 1000, ids[0]);
				Calendar cal = new GregorianCalendar(cest);
				String date = cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1)  + "-" + cal.get(Calendar.YEAR);
				
				//saves it in the database
				MetaData m = metaDataDatasource.createMetaData(titel.getText().toString(), PATH + titel.getText().toString(), date, "text", point);

				
				finish();
				
			}
			
		});
	}
}

